<template>
  <div>
    <a-modal
      ok-text="确认"
      cancel-text="取消"
      :maskClosable="false"
      :title="title"
      :destroyOnClose="true"
      :width="drawerWidth"
      @cancel="handleClose"
      :visible="visible"
      :confirmLoading="confirmLoading"
      @ok="onSubmit"
      footer=""
    >
      <template>
        <div class="modalBut">
          <a-button @click="handleClose">
            取消
          </a-button>
          <a-button @click="onSubmit" type="primary">确认</a-button>
        </div>
      </template>
      <div
        :style="{
          width: '100%',
          border: '1px solid #e9e9e9',
          padding: '10px 16px',
        }"
      >
        <a-spin :spinning="confirmLoading">
          <a-form-model ref="ruleForm" :model="model" :rules="rules">
            <a-row>
              <a-col :span="21">
                <a-row :gutter="24">
                  <a-col :span="8"
                    ><a-form-model-item
                      :labelCol="labelCol"
                      :wrapperCol="wrapperCol"
                      label="设备编号"
                      hasFeedback
                      prop="equipmentNumber"
                    >
                      <a-input
                        placeholder="请输入设备编号"
                        v-model.trim="model.equipmentNumber"
                      />
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="8">
                    <a-form-model-item
                      :labelCol="labelCol"
                      :wrapperCol="wrapperCol"
                      label="设备名称"
                      hasFeedback
                      prop="equipmentName"
                    >
                      <a-input
                        placeholder="请输入设备名称"
                        v-model.trim="model.equipmentName"
                      /> </a-form-model-item
                  ></a-col>
                  <a-col :span="8">
                    <a-form-model-item
                      :labelCol="labelCol"
                      :wrapperCol="wrapperCol"
                      label="设备型号"
                      hasFeedback
                      prop="equipmentModel"
                    >
                      <a-input
                        placeholder="请输入设备型号"
                        v-model.trim="model.equipmentModel"
                      />
                    </a-form-model-item>
                  </a-col>
                </a-row>
                <a-row :gutter="24">
                  <a-col :span="8">
                    <a-form-model-item
                      :labelCol="labelCol"
                      :wrapperCol="wrapperCol"
                      label="设备SN号"
                      hasFeedback
                      prop="macSn"
                    >
                      <a-input
                        v-model.trim="model.macSn"
                        placeholder="请输入设备SN号"
                        :disabled="disabled"
                      />
                    </a-form-model-item>
                  </a-col>

                  <a-col :span="8">
                    <a-form-model-item
                      label="选择产线"
                      :labelCol="labelCol"
                      :wrapperCol="wrapperCol"
                    >
                      <a-select
                        :allowClear="true"
                        v-model="model.productLineId"
                        placeholder="请选择产线"
                        @change="handleChange"
                      >
                        <a-select-option
                          v-for="(item, index) in Option"
                          :key="index"
                          :value="item.id"
                        >
                          {{ item.name }}
                        </a-select-option>
                      </a-select>
                    </a-form-model-item>
                  </a-col>
                  <a-col :span="8">
                    <a-form-model-item
                      :labelCol="labelCol"
                      :wrapperCol="wrapperCol"
                      label="设备图片"
                      hasFeedback
                      prop="pic"
                    >
                      <ImageUpload v-model.trim="model.pic"></ImageUpload>
                    </a-form-model-item>
                  </a-col>
                </a-row>
              </a-col>
            </a-row>
          </a-form-model>
        </a-spin>
      </div>
    </a-modal>
    <table-select-modal
      ref="selectForm"
      :columns="columns"
      :replaceFields="departReplace"
      :treeKey="treeKey"
      :tableKey="tableKey"
      @tableSelect="tableSelect"
      :name="name"
      :code="code"
      :filename="filename"
    ></table-select-modal>
    <table-Modal
      ref="tableForm"
      :columns="user"
      :tableKey="userTableKey"
      :treeKey="userTreeKey"
      @tableSelect="tableSelectUser"
      :replaceFields="userReplaceFields"
      :searchKey="userSearchKey"
      :name="userName"
      :filename="userfilename"
    ></table-Modal>
  </div>
</template>

<script>
import api from "@/api/apiServer";
import { apiUrl } from "@/api/URLConfig";
import { isNum } from "@/unit/rule.js";
import TableSelectModal from "@/components/TableSelectModal";
import ImageUpload from "@/components/upload/ImageUpload.vue";
import TableModal from "@/components/TableSelectModal";
import { departColumns } from "@/pages/EquipMentRegister/components/tableConfig";
import { user } from "@/unit/tableUser.js";
export default {

  components: { TableSelectModal, TableModal, ImageUpload },
  data() {
    return {
      disabled: false,
      Option:[],
      title: "", // 标题
      visible: false, // 状态、
      drawerWidth: 1677, // 抽屉宽度
      model: {},
      show: true, //根据菜单类型，动态显示隐藏表单元素
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      tableOption: [],
      tableUserOption: [],
      manufacturerOption: [],
      replaceFields: {
        children: "equipmentTypeList",
        title: "equipmentTypeName",
        key: "id",
        value: "id",
      },
      departReplace: {
        children: "childList",
        title: "departmentName",
        key: "id",
        value: "id",
      },
      columns: departColumns,
      treeKey: "DepartmentTree",
      tableKey: "DepartmentList",
      name: "departmentName",
      code: "departmentNumber",
      filename: "DepartmentModal",
      user,
      userReplaceFields: {
        children: "childList",
        title: "departmentName",
        key: "id",
        value: "id",
      },
      userTreeKey: "DepartmentTree",
      userTableKey: "UserList",
      userSearchKey: "departmentId",
      userName: "name",
      userfilename: "UserModal",
      // 联网方式
      networkWayOption: [],
      apiUrl
    };
  },
  computed: {
    rules() {
      return {
        equipmentNumber: [{ required: true, message: "请输入设备编号!" }],
        equipmentName: [{ required: true, message: "请输入设备名称!" }],
        equipmentModel: [{ required: true, message: "请输入设备型号!" }],
        macSn: [{ required: true, message: "请输入设备SN号!" }],
        equipmentWeight: [{ validator: isNum, trigger: "change" }],
      };
    },
  },
  methods: {
    // 新增
    modalAdd() {
      this.disabled = false;
      this.getautoCoding();
      this.getOption()
      this.modalEdit({});
    },
    // 编辑
    modalEdit(record) {
      console.log(record);
      this.getOption()
      this.resetScreenSize();
      this.visible = true;
      this.getDictFindByCode("dict.equipment.manufacturer", "manufacturer");
      this.getDictFindByCode("dict.networkWay", "networkWay");
      console.log(this.Option, "90909090909");
      if (record.id) {
        record.manufacturer = Number(record.manufacturer);
        this.disabled = true;
        this.getDepartAllList();
        this.getUserAllList();
      }
      this.model = Object.assign({}, record);
      if (this.model.departmentId === null) {
        delete this.model.departmentId;
      }

      if (this.model.managementPersonId === null) {
        delete this.model.managementPersonId;
      }
      if (this.model.manufacturer === 0) {
        delete this.model.manufacturer;
      }
    },
    // 获取数据来源
    async getDictFindByCode(parentCode, Key) {
      const res = await api.DictFindByCode({ parentCode });
      this[Key + "Option"] = res.data;
    },
    async getOption() {
      const params = { pageNumber: 1, pageSize: 999999 };
      const res = await api.ProductLinePage(params);
      // this.treeData = setTreeData(res.data.data, "custom", "equipmentTypeList");
      this.Option = res.data.data;
      this.Option.push({
        id: -1,
        name: "未分组",
      });
      this.Option.push({
        id: -2,
        name: "报废组",
      });
    },
    //自动生成sn
    async getautoCoding() {
      const res = await api.autoCoding({ type: "SN" });
      console.log(res, "SNSNS");
      this.$set(this.model, "macSn", res.data);
    },
    onChangeMenuType() {},
    // 关闭
    handleClose() {
      this.visible = false;
      this.$refs.ruleForm.resetFields();
      this.model = Object.assign({});
      this.$emit('cancel')
    },

    onSubmit() {
      const that = this;
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          that.handleSubmit();
        } else {
          return false;
        }
      });
    },
    // 获取部门数据
    async getDepartAllList() {
      let params = { pageNumber: 1, pageSize: 99999, deleteFlag: "N" };
      const res = await api.DepartmentList(params);
      this.tableOption = res.data.data;
    },
    // 获取负责人数据
    async getUserAllList() {
      let params = { pageNumber: 1, pageSize: 99999, deleteFlag: "N" };
      const res = await api.UserList(params);
      this.tableUserOption = res.data.data;
    },
    async handleSubmit() {
      let res;
      this.confirmLoading = true;
      this.model.directCollection = true;
      this.model.directDelivery = true;
      if (this.model.id) {
        res = await api.equipmentEdit(this.model); //修改
      } else {
        res = await api.equipmentAdd(this.model); //新增
      }
      if (res.code && res.code !== 200) {
        this.$message.error(res.message);
        this.confirmLoading = false;
        return;
      }
      this.$message.success(res.message);
      this.confirmLoading = false;
      this.$emit("ok");
      this.visible = false;
    },
    // 根据屏幕变化,设置抽屉尺寸
    resetScreenSize() {
      let screenWidth = document.body.clientWidth;
      if (screenWidth < 500) {
        this.drawerWidth = screenWidth;
      } else {
        this.drawerWidth = 1677;
      }
    },
    handleDepar() {
      this.$refs.selectForm.title = "部门";
      this.$refs.selectForm.modalAdd();
      if (this.model.departmentId) {
        let arr = this.model.departmentId.toString().split(",");
        if (arr.length > 0) {
          let newArr = arr.map((item) => {
            return Number(item);
          });
          this.$refs.selectForm.selectedRowKeys = newArr;
        } else {
          this.$refs.selectForm.selectedRowKeys = [];
        }
      }
    },
    handleDearChange(value) {
      if (value.length > 0) {
        this.model.departmentId = value.toString();
      } else {
        delete this.model.departmentId;
      }
    },
    tableSelect(result, tableOption) {
      this.tableOption = tableOption;
      this.$set(this.model, "departmentId", result[0].id);
      this.$set(this.model, "userDepartment", result[0].departmentName);
    },
    handlePerson() {
      this.$refs.tableForm.title = "人员";
      this.$refs.tableForm.modalAdd();
      if (this.model.managementPersonId) {
        let arr = this.model.managementPersonId.toString().split(",");
        if (arr.length > 0) {
          let newArr = arr.map((item) => {
            return Number(item);
          });
          this.$refs.tableForm.selectedRowKeys = newArr;
        } else {
          this.$refs.tableForm.selectedRowKeys = [];
        }
      }
    },
    tableSelectUser(result, tableUserOption) {
      this.tableUserOption = tableUserOption;
      this.$set(this.model, "managementPersonId", result[0].id);
      this.$set(this.model, "managementResponsiblePerson", result[0].name);
    },
    handlePersonChange(value) {
      if (value.length > 0) {
        this.model.managementPersonId = value.toString();
      } else {
        delete this.model.managementPersonId;
      }
    },
    handleChange(value) {
      this.model.productLineId = value;
      this.$emit("ok");
    },
  },
};
</script>

<style></style>
